package com.zyw.weibo.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.emagsoftware.content.pm.PackageMgr;
import cn.emagsoftware.ui.ToastManager;
import cn.emagsoftware.ui.adapterview.AsyncDataExecutor;
import cn.emagsoftware.ui.adapterview.AsyncDataScheduler;
import cn.emagsoftware.ui.adapterview.BaseStepLoadingAdapter;
import cn.emagsoftware.ui.adapterview.DataHolder;
import cn.emagsoftware.ui.adapterview.ViewHolder;
import cn.emagsoftware.util.LogManager;

import com.zyw.weibo.Utilities;
import com.zyw.weibo.data.User;
import com.zyw.weibo.data.UserListResult;
import com.zyw.weibo.data.Weibo;
import com.zyw.weibo.data.WeiboResult;
import com.zyw.weibo.data.remote.NetEngine;
import com.zyw.weibo.data.remote.NetOperatingManager;
import com.zyw.weibo.ui.support.WeiboAsyncDataExecutor;
import com.zyw.weibo.ui.support.WeiboDataHolder;

public class Search extends Base {
	
	public static final String KEY_WORDS = "WORDS";
	public static final String KEY_CONDITION = "CONDITION";
	public static final String VALUE_CONDITION_WEIBO = "WEIBO";
	public static final String VALUE_CONDITION_USER = "USER";
	
	private AsyncDataScheduler searchScheduler = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		if(!Welcome.IS_APP_RUNNING){
			Intent intent = PackageMgr.getLaunchIntentForPackage(this, getPackageName());
			startActivity(intent);
			finish();
			return;
		}
		setContentView(R.layout.search);
		
		Intent intent = getIntent();
		String words = intent.getStringExtra(KEY_WORDS);
		String condition = intent.getStringExtra(KEY_CONDITION);
		if(words == null || condition == null) finish();
		
		Button topLeftBtn = (Button)findViewById(R.id.btnTopbarLeft);
		Button homeTitle = (Button)findViewById(R.id.btnTopbarCenter);
		Button topRightBtn = (Button)findViewById(R.id.btnTopbarRight);
		topLeftBtn.setBackgroundResource(R.drawable.generic_btn_back_selector);
		homeTitle.setText(R.string.search_title);
		topRightBtn.setBackgroundResource(R.drawable.generic_btn_reload_selector);
		topLeftBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		topRightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				BaseStepLoadingAdapter searchAdapter = (BaseStepLoadingAdapter)searchScheduler.getViewAdapter();
				if(!searchAdapter.isLoading()){
					searchAdapter.clearDataHolders();
					searchAdapter.load(null);
				}
			}
		});
		
		initSearch(words,condition);
	}
	
	private void initSearch(String words,String condition){
		final EditText input = (EditText)findViewById(R.id.etSearchInput);
		final Button clear = (Button)findViewById(R.id.btnSearchClear);
		input.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				if(TextUtils.isEmpty(s)) clear.setVisibility(View.GONE);
				else clear.setVisibility(View.VISIBLE);
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub
			}
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
			}
		});
		input.setText(words);
		input.setSelection(words.length());
		clear.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				input.setText("");
			}
		});
		Button weibo = (Button)findViewById(R.id.btnSearchWeibo);
		Button user = (Button)findViewById(R.id.btnSearchUser);
		final ImageView weiboSelected = (ImageView)findViewById(R.id.ivSearchWeiboSelected);
		final ImageView userSelected = (ImageView)findViewById(R.id.ivSearchUserSelected);
		if(condition.equals(VALUE_CONDITION_WEIBO)){
			weiboSelected.setImageResource(R.drawable.search_icon_selected);
			userSelected.setImageResource(R.drawable.search_icon_unselected);
		}else{
			weiboSelected.setImageResource(R.drawable.search_icon_unselected);
			userSelected.setImageResource(R.drawable.search_icon_selected);
		}
		final String[] curCondition = new String[]{condition};
		weibo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				weiboSelected.setImageResource(R.drawable.search_icon_selected);
				userSelected.setImageResource(R.drawable.search_icon_unselected);
				curCondition[0] = VALUE_CONDITION_WEIBO;
				String inputStr = input.getText().toString();
				if(TextUtils.isEmpty(inputStr)){
					ToastManager.showLong(Search.this, R.string.main_square_search_empty);
					return;
				}
				search(inputStr,curCondition[0]);
			}
		});
		user.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				weiboSelected.setImageResource(R.drawable.search_icon_unselected);
				userSelected.setImageResource(R.drawable.search_icon_selected);
				curCondition[0] = VALUE_CONDITION_USER;
				String inputStr = input.getText().toString();
				if(TextUtils.isEmpty(inputStr)){
					ToastManager.showLong(Search.this, R.string.main_square_search_empty);
					return;
				}
				search(inputStr,curCondition[0]);
			}
		});
		Button search = (Button)findViewById(R.id.btnSearchSearch);
		search.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String inputStr = input.getText().toString();
				if(TextUtils.isEmpty(inputStr)){
					ToastManager.showLong(Search.this, R.string.main_square_search_empty);
					return;
				}
				search(inputStr,curCondition[0]);
			}
		});
		search(words,curCondition[0]);
	}
	
	private RelativeLayout listLoadingView = null;
	private void search(final String words,final String condition){
		BaseStepLoadingAdapter searchAdapter = null;
		if(searchScheduler != null) searchAdapter = (BaseStepLoadingAdapter)searchScheduler.getViewAdapter();
		if(searchAdapter == null || !searchAdapter.isLoading()){
			ListView searchList = (ListView)findViewById(R.id.lvSearchList);
			if(searchAdapter != null){
				searchList.removeFooterView(listLoadingView);
				searchScheduler.stop();
			}
			listLoadingView = (RelativeLayout)getLayoutInflater().inflate(R.layout.generic_loading, null);
			final ProgressBar listProgressBar = (ProgressBar)listLoadingView.findViewById(R.id.pbLoadingProgress);
			final TextView listProgressDes = (TextView)listLoadingView.findViewById(R.id.tvLoadingDes);
			final Button listRetry = (Button)listLoadingView.findViewById(R.id.btnLoadingRetry);
			int footSpace = (int)getResources().getDimension(R.dimen.main_index_listfoot_space_vertical);
			listLoadingView.setPadding(0, footSpace, 0, footSpace);
			searchList.addFooterView(listLoadingView, null, true);
			final BaseStepLoadingAdapter curSearchAdapter = new BaseStepLoadingAdapter(this) {
				@Override
				public void onBeginLoad(Context arg0, Object arg1) {
					// TODO Auto-generated method stub
					listProgressBar.setVisibility(View.VISIBLE);
					listProgressDes.setVisibility(View.VISIBLE);
					listProgressDes.setText(R.string.generic_loading_loading);
					listRetry.setVisibility(View.GONE);
				}
				@Override
				public List<DataHolder> onLoad(Context arg0, Object arg1, int arg2, int arg3) throws Exception {
					// TODO Auto-generated method stub
					List<DataHolder> holders = new ArrayList<DataHolder>();
					if(condition.equals(VALUE_CONDITION_WEIBO)){
						WeiboResult result = NetOperatingManager.searchWeibo(arg0, arg3, LIST_LAZYLOADING_LIMIT, words);
						setPages(Integer.valueOf(result.pages));
						for(Weibo wb:result.list){
							int asyncDataCount = 0;
							if(!TextUtils.isEmpty(wb.blogsender.selfpicture)) asyncDataCount = asyncDataCount + 1;
							if(wb.image != null) asyncDataCount = asyncDataCount + 1;
							if(wb.originalblogid != null && wb.originalblogid.image != null) asyncDataCount = asyncDataCount + 1;
							holders.add(new WeiboDataHolder(wb, asyncDataCount, Utilities.getBlogfrom(arg0, wb.blogfrom)));
						}
					}else{
						UserListResult result = NetOperatingManager.searchUser(arg0, arg3, LIST_LAZYLOADING_LIMIT, words);
						setPages(Integer.valueOf(result.pages));
						for(User user:result.list){
							holders.add(new DataHolder(user,TextUtils.isEmpty(user.selfpicture)?0:1) {
								@Override
								public View onCreateView(Context arg0, int arg1, Object arg2) {
									// TODO Auto-generated method stub
									RelativeLayout wrap = (RelativeLayout)LayoutInflater.from(arg0).inflate(R.layout.search_user_list_item, null);
									ImageView head = (ImageView)wrap.findViewById(R.id.ivSearchHead);
									TextView name = (TextView)wrap.findViewById(R.id.tvSearchName);
									TextView fans = (TextView)wrap.findViewById(R.id.tvSearchFans);
									ViewHolder viewHolder = new ViewHolder(head,name,fans);
									wrap.setTag(viewHolder);
									onUpdateView(arg0,arg1,wrap,arg2,false);
									return wrap;
								}
								@Override
								public void onUpdateView(Context arg0, int arg1, View arg2, Object arg3, boolean arg4) {
									// TODO Auto-generated method stub
									User user = (User)arg3;
									View[] views = ((ViewHolder)arg2.getTag()).getParams();
									ImageView head = (ImageView)views[0];
									TextView name = (TextView)views[1];
									TextView fans = (TextView)views[2];
									if(TextUtils.isEmpty(user.selfpicture)) {
										head.setImageResource(R.drawable.main_index_list_item_defualthead);
									}else{
										Object asyncData = getAsyncData(0);
										if(asyncData == null) head.setImageResource(R.drawable.main_index_list_item_defualthead);
										else head.setImageDrawable((Drawable)asyncData);
									}
									name.setText(user.nickname);
									fans.setText(arg0.getString(R.string.search_user_list_item_fans).replace("{0}", user.concernedcount));
								}
							});
						}
					}
					return holders;
				}
				@Override
				public void onAfterLoad(Context arg0, Object arg1, Exception arg2) {
					// TODO Auto-generated method stub
					if(arg2 == null){
						listProgressBar.setVisibility(View.GONE);
						listProgressDes.setVisibility(View.VISIBLE);
						if(isLoadedAll()) listProgressDes.setText(R.string.generic_loading_loadcomplete);
						else listProgressDes.setText(R.string.generic_loading_load);
						listRetry.setVisibility(View.GONE);	
					}else{
						LogManager.logE(Search.class, "load failed.", arg2);
						listProgressBar.setVisibility(View.GONE);
						listProgressDes.setVisibility(View.GONE);
						listRetry.setVisibility(View.VISIBLE);
					}
				}
			};
			
			listRetry.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					curSearchAdapter.load(null);
				}
			});
			searchList.setAdapter(curSearchAdapter);
			searchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// TODO Auto-generated method stub
					if(arg2 >= curSearchAdapter.getCount()){
						if(!curSearchAdapter.isLoadedAll()) curSearchAdapter.load(null);
					}else{
						if(condition.equals(VALUE_CONDITION_WEIBO)){
							Weibo wb = (Weibo)curSearchAdapter.queryDataHolder(arg2).getData();
							Intent detailIntent = new Intent(Search.this, Detail.class);
							detailIntent.putExtra("weibo", wb);
							startActivity(detailIntent);
						}else{
							User user = (User)curSearchAdapter.queryDataHolder(arg2).getData();
							Intent userDetailIntent = new Intent(Search.this, UserDetail.class);
							userDetailIntent.putExtra(UserDetail.KEY_NAME, user.nickname);
							startActivity(userDetailIntent);
						}
					}
				}
			});
			if(condition.equals(VALUE_CONDITION_WEIBO)){
				searchScheduler = new AsyncDataScheduler(searchList, LIST_ASYNCEXECUTING_THREADCOUNT, new WeiboAsyncDataExecutor(this,(int)getResources().getDimension(R.dimen.main_index_list_item_image_maxwidth)));
			}else{
				searchScheduler = new AsyncDataScheduler(searchList, LIST_ASYNCEXECUTING_THREADCOUNT, new AsyncDataExecutor(1,1) {
					@Override
					public void onExecute(List<Integer> arg0, List<DataHolder> arg1, List<Integer> arg2) throws Exception {
						// TODO Auto-generated method stub
						DataHolder holder = arg1.get(0);
						User user = (User)holder.getData();
						String url = NetOperatingManager.URL_HOST + user.selfpicture;
						byte[] data = NetEngine.requestImage(Search.this, url);
						Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
						if(bitmap != null) holder.setAsyncData(0, new BitmapDrawable(bitmap));
					}
				});
			}
			
			curSearchAdapter.load(null);
			searchScheduler.start();
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		searchScheduler.stop();
		searchScheduler = null;
	}
	
}
